package com.feib.ebilling.job.service;

import org.springframework.stereotype.Service;

import it.sauronsoftware.ftp4j.FTPClient;
import java.security.*;
import java.security.cert.X509Certificate;
import javax.net.ssl.*;

@Service("ftpSSLService")
public class FtpSSLService extends BaseService {
	
	public boolean getFile(String sFileName,String remoteFolder, String host, String username, String password, String localFolder) throws Exception {

		try {
			TrustManager[] trustManager = new TrustManager[] { new X509TrustManager() {
				public X509Certificate[] getAcceptedIssuers() {
					return null;
				}
				public void checkClientTrusted(X509Certificate[] certs, String authType) {
				}
				public void checkServerTrusted(X509Certificate[] certs, String authType) {
				}
			} };
			SSLContext sslContext = null;
			FTPClient client = new FTPClient();	
			
			try {
				sslContext = SSLContext.getInstance("SSL");
				sslContext.init(null, trustManager, new SecureRandom());
				SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
				//SSLSocketFactory sslSocketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
				client.setSSLSocketFactory(sslSocketFactory);
				client.setSecurity(FTPClient.SECURITY_FTPES);
				//client.setSecurity(FTPClient.SECURITY_FTPS);
			} catch (NoSuchAlgorithmException e) {
				e.printStackTrace();
			} catch (KeyManagementException e) {
				e.printStackTrace();
			}	
		
			logger.info("open ftps");
			client.connect(host, 21);
			logger.info("connect ftps");
			/* 登入帳號 */			
			logger.info("login");
			client.login(username, password);			
			/* 切換目錄 */
			client.changeDirectory(remoteFolder);
			String dir = client.currentDirectory();
			logger.info("Current Directory {}" ,dir);
			/* 下載檔案 */
			client.download(sFileName, new java.io.File(localFolder + "\\" + sFileName));		 
			client.disconnect(true);
			logger.info("close ftps");
		    return true;
		}catch (Exception ex){
			logger.info(ex.toString(), ex);
		    return false;
        }
	}	
}


